import { Component, OnInit } from "@angular/core";
import { HttpServcie } from "../../service/http.service";
import { Router } from "@angular/router";
import { NzNotificationService, NzModalSubject, NzModalService } from "ng-zorro-antd";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";
import { Config } from "../../service/config";
import * as moment from "moment";
import {InformationAgent} from "./information/bean/informationAgent";

@Component({
  selector: "page-home",
  templateUrl: "home.html",
  styleUrls: ["home.scss"]
})
export class Home implements OnInit {
  currentModal: NzModalSubject;
  showWz = false;
  modelTitle;
  modal;
  informationAgent:InformationAgent = new InformationAgent();
  // 定义数据对象用于界面
  public planData:any=[];
  dot = false;

  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private modalService: NzModalService
  ) {
    if ((window.location.href + "").indexOf("wzscjg.hyjckj.net") >= 0) {
      this.showWz = true;
    }
  }
  menuList: any = [];
  isAdmin: any = false;
  sysUser: any;
  empiric: any = 0;
  grade: any;
  newpwd: any;
  oldpwd: any;
  newpwd2: any;
  newphone: any;
  partySeleList = [];
  toParty: any;
  partyType : any;
  mark = 0;
  ngOnInit() {
    if (window.localStorage.getItem("user")) {
      this.sysUser = JSON.parse(window.localStorage.getItem("user"));
      this.partyType = this.sysUser.partyType;
      if(this.sysUser.mark != null && this.sysUser.mark > 0){
        this.mark = this.sysUser.mark;
      }
    } else {
      this.router.navigateByUrl("/login");
      return;
    }

    this.httpServcie.user().subscribe(
      data => {
        if (data.status === 200) {
          this.menuList = data.data;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
    this.isAdmin = this.sysUser.userCode == "admin";

    //查积分
    if (this.sysUser.partyType == '1' || this.sysUser.partyType == '2') {
      let param = {
        type: '',
        userId: ''
      }
      param.type = this.sysUser.partyType;
      param.userId = this.sysUser.partyId;
      if (this.sysUser.roleName == '电梯维保人员') {
        param.type = '4';
        param.userId = this.sysUser.id;
      }
      if (this.sysUser.roleName == '电梯安全管理员') {
        param.type = '3';
        param.userId = this.sysUser.id;
      }

      this.httpServcie.queryEmpiric(param).subscribe(data => {
        console.log(data)
        if (data.status == '200') {
          this.empiric = data.data.empiricValue;
          this.grade = data.data.grade;
        }
      });

    }

    if(this.sysUser.roleId=='17'){
      this.queryData();
    }

  }



  extit() {
    this.router.navigateByUrl("/login");
  }

  goHome() {
    this.router.navigateByUrl("/home/main");
  }

  fileUploader = new FileUploader({
    url: Config.IP + Config.API.uploadRootData,
    method: "POST",
    itemAlias: "file",
    autoUpload: false,
    headers: [
      { name: "Authorization", value: "Bearer " + window.localStorage["token"] }
    ]
  });

  //选择文件后调用的方法
  selectedFileOnChanged(event) {
    //手动上传的
    this.fileUploader.uploadAll();
    this.fileUploader.onSuccessItem = (
      item: FileItem,
      response: string,
      status: number,
      headers: ParsedResponseHeaders
    ) => {
      if (status == 200) {
        //判断是否是图片
        JSON.parse(response).data;
      }
    };
  }

  showph(titlepass, contentpass, footerpass) {
    this.newphone = "";
    this.currentModal = this.modalService.open({
      title: titlepass,
      content: contentpass,
      footer: footerpass,
      maskClosable: false,
      width: 500,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  showpwd(titlepass, contentpass, footerpass) {
    this.oldpwd = "";
    this.newpwd = "";
    this.newpwd2 = "";
    this.currentModal = this.modalService.open({
      title: titlepass,
      content: contentpass,
      footer: footerpass,
      maskClosable: false,
      width: 500,
      style: {
        top: "20px"
      },

      onOk() {
        console.log("Click ok");
      }
    });
  }

  addMeatasisDialog(titleTpl, contentTpl, footerTpl) {

    this.querySameParty();
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  querySameParty() {
    let parentId = JSON.parse(window.localStorage.getItem("user"))
      .partyParentId;
    this.httpServcie
      .queryByIdAndTypeList({
        // id: parentId,
        partyType: JSON.parse(window.localStorage.getItem("user")).partyType
      })
      .subscribe(data => {
        if (data.status == 200) {
          //物业机构
          this.partySeleList = data.data;
        }
      });
  }

  addMeatasis() {
    let type = "";
    if (this.sysUser.roleName == '电梯维保人员') {
      type = '4';
    }
    if (this.sysUser.roleName == '电梯安全管理员') {
      type = '3';
    }

    let newPartyId = this.sysUser.partyId;
    if (this.toParty) {
      newPartyId = this.toParty;
    }

    let toName = "";
    for (let party of this.partySeleList) {
      if (newPartyId == party.id) {
        toName = party.partyName;
        break;
      }
    }
    let param = {
      userId: this.sysUser.id,
      userName: this.sysUser.userName,
      fromId: this.sysUser.partyId,
      fromName: this.sysUser.partyName,
      toId: newPartyId,
      toName: toName,
      state: "1"
    };
    this.httpServcie.addMeatasis(param).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "提交转移申请成功！");
        this.currentModal.destroy();
      } else if (data.status === 401) {
        this._notification.create("success", "提示", "登录超时，请重新登录");
        this.router.navigateByUrl("/login");
        return;
      } else {
        // 异常
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  changePass() {
    if (!this.oldpwd || !this.newpwd || !this.newpwd2) {
      this._notification.create("warning", "警告提示", "请填写完整");
      return;
    }
    if (this.newpwd != this.newpwd2) {
      this._notification.create("warning", "警告提示", "两次输入的新密码不正确");
      return;
    }

    let param = {
      id: this.sysUser.id,
      oldpwd: this.oldpwd,
      newpwd: this.newpwd
    }
    this.httpServcie.updateUserPwd(param).subscribe(data => {
      if (data.status == '200') {
        this._notification.create("success", "成功提示", "修改成功,请重新登录");
        this.currentModal.destroy();
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    })



  }

  changePhone() {
    if(this.newphone =="" || this.newphone==null || this.newphone==undefined){
      this._notification.create("warning", "警告提示", "手机号码不能为空");
      return;
    }else{
      let reg = /^1[0-9]{10}$/;
      if(!reg.test(this.newphone)){
        this._notification.create("error", "错误提示", "请输入正确的手机号码");
        return;
      }
    }
    let param = {
      id: this.sysUser.id,
      newphone: this.newphone
    }
    this.httpServcie.updateUserPhone(param).subscribe(data => {
      if (data.status == '200') {
        this._notification.create("success", "成功提示", "修改成功");
        this.currentModal.destroy();
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  // 添加界面打开
  // 添加界面打开
  add(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "待办列表";
    this.modal = 0;
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }


  //查询代办信息列表
  queryData() {
    var startTime =  moment(new Date()).format("YYYY-MM-DD");
    this.informationAgent.startTime =moment(startTime).format("YYYYMMDD");
    this.informationAgent.isCheck='N';

    this.httpServcie.informationAgent(this.informationAgent).subscribe(data => {
      if (data.status == "200") {
        console.log(data);
        if (data.data.length>0) {
          this.dot = true;
          this.planData = data.data;
        } else {
          this.planData = [];
        }
        console.log(this.planData);
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  // 添加后界面刷新
  addOutPut(event) {
    setTimeout(() => {
      this.currentModal.destroy();
      this.currentModal = null;
    }, 200);
  }


}
